<template>
  <div @click="filterChangeRef.gradeAndClassOpen = false">
    <!-- 表单查询 -->
    <div class="top">
      <TabList @onTabsValue="onTabsValue" />
      <Form
        ref="formRef"
        name="advanced_search"
        class="ant-advanced-search-form"
        :model="formState"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <Row :gutter="[16, 1]" style="margin-right: 16px">
          <Col :span="6">
            <Form.Item label="宿舍楼" name="dormitoryId">
              <a-select
                ref="select"
                v-model:value="formState.dormitoryId"
                placeholder="请选择"
                allow-clear
                :get-popup-container="
                  triggerNode => {
                    return triggerNode.parentNode;
                  }
                "
                @change="onSelectDormitory"
              >
                <a-select-option
                  v-for="(item, index) of optionList.dormitoryList"
                  :key="index"
                  :value="item.id"
                  >{{ item.name }}</a-select-option
                >
              </a-select>
            </Form.Item>
          </Col>
          <Col :span="6">
            <Form.Item label="房间名" name="roomId">
              <!-- <a-select ref="select" v-model:value="formState.roomId">
                <a-select-option value="">全部</a-select-option>
              </a-select> -->
              <a-cascader
                v-model:value="formState.roomId"
                allow-clear
                :options="optionList.roomList"
                placeholder="请选择"
                :load-data="onLoadDataRoom"
                :field-names="{ label: 'name', value: 'id' }"
                :get-popup-container="
                  triggerNode => {
                    return triggerNode.parentNode;
                  }
                "
                @change="onChangeRoom"
              />
            </Form.Item>
          </Col>
          <Col :span="6">
            <Form.Item label="姓名" name="studentName">
              <a-input
                v-model:value="formState.studentName"
                autocomplete="off"
                allow-clear
                placeholder="请输入"
                :max-length="30"
              ></a-input>
            </Form.Item>
          </Col>
          <Col :span="6">
            <Form.Item label="年级/班级" name="gradeId">
              <FilterChange ref="filterChangeRef" />
            </Form.Item>
          </Col>
          <Col :span="9">
            <Form.Item
              v-if="activeKey !== 'all'"
              name="time"
              label="检查时间"
              :label-col="{ md: 5, lg: 5, xl: 5, xxl: 4 }"
            >
              <!-- :default-value="[
                  moment(startTime, 'YYYY-MM-DD HH:mm:ss'),
                  moment(endTime, 'YYYY-MM-DD HH:mm')
                ]" -->
              <!-- :value="getDateRange(startTime, endTime)" -->

              <a-range-picker
                :show-time="{ format: 'HH:mm' }"
                format="YYYY-MM-DD HH:mm"
                :placeholder="['开始日期', '结束日期']"
                :value="formState.createValue"
                :get-calendar-container="
                  triggerNode => {
                    return triggerNode.parentNode;
                  }
                "
                :allow-clear="true"
                @change="examineTime"
              />
            </Form.Item>
            <Form.Item
              v-else
              name="time"
              label="统计周期"
              :label-col="{ md: 5, lg: 5, xl: 5, xxl: 4 }"
            >
              <!-- :default-value="[
                  moment(startTime, 'YYYY-MM-DD HH:mm:ss'),
                  moment(endTime, 'YYYY-MM-DD HH:mm')
                ]" -->
              <!-- :value="getDateRange(startTime, endTime)" -->

              <a-range-picker
                :show-time="{ format: 'HH:mm' }"
                format="YYYY-MM-DD HH:mm"
                :placeholder="['开始日期', '结束日期']"
                :value="formState.createValue"
                :get-calendar-container="
                  triggerNode => {
                    return triggerNode.parentNode;
                  }
                "
                :allow-clear="false"
                @change="examineTime"
              />
            </Form.Item>
          </Col>
        </Row>
        <div class="search">
          <div class="search-btn">
            <a-button type="primary" html-type="submit" @click="onSearch(1)">查询</a-button>
            <a-button ghost style="margin: 0 0 0 16px" @click="onReset">重置</a-button>
          </div>
        </div>
      </Form>
    </div>
    <!-- 列表 -->
    <div class="below">
      <div v-if="activeKey === 'all' && rankingState" class="ranking">
        <span class="ranking-text">排名</span>
        <CloseOutlined style="font-size: 20px; color: #c2c2c2; cursor: pointer" @click="close" />
      </div>
      <div class="search">
        <div class="search-btn-right">
          <a-button
            v-if="activeKey === 'all' && rankingState && rankingOrder"
            type="primary"
            style="margin-right: 16px; display: flex; align-items: center"
            html-type="submit"
            ghost
            @click="asc"
          >
            <template #icon><SwapOutlined :style="{ transform: 'rotateZ(90deg)' }" /></template>
            正序
          </a-button>
          <a-button
            v-if="activeKey === 'all' && rankingState && !rankingOrder"
            type="primary"
            style="margin-right: 16px; display: flex; align-items: center"
            html-type="submit"
            ghost
            @click="desc"
          >
            <template #icon><SwapOutlined :style="{ transform: 'rotateZ(90deg)' }" /></template>
            反序
          </a-button>
          <a-button
            v-if="activeKey === 'all' && !rankingState"
            type="primary"
            style="margin-right: 16px; display: flex; align-items: center"
            html-type="submit"
            ghost
            @click="ranking()"
          >
            <template #icon><ToTopOutlined /></template>
            查看排行
          </a-button>
          <a-button
            :type="delStateClick"
            :ghost="isStudentLeadingOut"
            :loading="btnLoading"
            style="margin-right: 16px; display: flex; align-items: center"
            @click="leadingOut"
          >
            <template #icon><ToTopOutlined /></template>
            导出
          </a-button>
        </div>
      </div>
      <!-- 表格 -->
      <div>
        <a-table
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          :columns="columns"
          :data-source="tableData.records"
          :row-key="record => (activeKey === 'all' ? record.studentUserId : record.markStudentId)"
          :pagination="false"
          :loading="loading"
          :scroll="{ x: 1300 }"
        >
          <!-- <template v-slot:emptyText>{{ loading ? '' : '暂无数据' }}</template> -->
          <template v-slot:emptyText>
            <div class="zz-global-nodata">
              <img
                v-if="searchStatus * 1 === 0"
                src="@/assets/images/accommodation/default-no-data.png"
                alt=""
              />
              <img v-else src="@/assets/images/accommodation/no-data-search-new.png" alt="" />
            </div>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'itemNames'">
              <div
                style="
                  font-size: 14px;
                  color: #222222;
                  width: 120px;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                "
              >
                <Tooltip
                  :overlay-style="{ whiteSpace: 'normal' }"
                  :get-popup-container="
                    triggerNode => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  placement="topLeft"
                  :title="record.itemNames"
                >
                  {{ record.itemNames }}
                </Tooltip>
              </div>
            </template>

            <template v-if="column.dataIndex === 'action'">
              <a-button
                type="primary"
                size="small"
                ghost
                class="z-btn-24"
                @click="onDeta(record.examineId, record.studentUserId, record.roomId)"
                >查看</a-button
              >
            </template>
          </template>
        </a-table>
      </div>
      <!-- 分页 -->
      <div class="pagination">
        <span style="color: #999999; margin-right: 8px">共{{ tableData.pages }}页</span>
        <a-pagination
          v-model:current="tableData.current"
          v-model:pageSize="tableData.size"
          :page-size-options="pageSizeOptions"
          show-quick-jumper
          :total="tableData.total"
          :show-size-changer="true"
          @change="onChangePagination"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch, computed } from 'vue';
import { useRouter } from 'vue-router';
import { Form, Row, Col, Message, Cascader, Tooltip, message } from 'ant-design-vue';
import { ToTopOutlined, CloseOutlined, SwapOutlined } from '@ant-design/icons-vue';
import {
  getAssessList,
  listRankStudentExamine,
  exportSummaryStudentExamine,
  exportRankStudentExamine,
  exportStudentExamine,
  getStudentExamineDetails,
  getStudentDayExamineDetail
} from '@/api/assessment/dormitoryPersonal';
import { getDormitory, floorList, floorRoom, roomBedNum, gradeList, classList } from '@/api/common';
import TabList from '../components/tebPane/TabPane.vue';
import dayjs from 'dayjs';
import moment from 'moment';
import { useStore } from 'vuex';
import FilterChange from '@/components/filterChange/index.vue';
import { debounce } from '@/utils/debounce.js';
// 表格信息
const tableData = ref([]);
const router = useRouter();
const dayCreateValue = ref([]);
const localStorageSchoolId = localStorage.getItem('localStorageSchoolId');
const schoolBaseId = ref(0);
const formState = ref({
  superiorId: 0, // 考核分类，0为综合查询 其余分类依照学校设置为准
  studentName: '', // 姓名
  releaseUserName: '',
  gradeId: undefined, // 年级
  classId: undefined, // 班级
  dormitoryId: undefined, // 宿舍楼
  sex: '', // 性别
  roomId: [], // 房间名称
  studentState: '', // 学生状态
  allocationStatus: '', // 分配状态
  examineStartTime: '', // 开始时间
  examineStopTime: '', // 结束时间
  createValue: dayCreateValue.value,
  size: tableData.value.size, // 条数
  current: tableData.value.current // 页码
});
const searchStatus = ref(0);
// tabs 激活标签
const activeKey = ref('');
onMounted(() => {
  dataForm();
  // getRoomBedNum();
  // getDormitoryList();

  let dormitoryUserQuery = localStorage.getItem('dormitoryUserQuery');
  if (!dormitoryUserQuery || dormitoryUserQuery === null || dormitoryUserQuery === undefined) {
    console.log('走进来了吗。。。。');
    dayCreateValue.value = [
      dayjs(moment().format('YYYY-MM-DD 00:00')),
      dayjs(moment().format('YYYY-MM-DD 23:59'))
    ];
  }
  if (
    localStorageSchoolId === '346001568933441537' ||
    localStorageSchoolId === '221954838718582784'
  ) {
    schoolBaseId.value = 1;
  } else {
    schoolBaseId.value = 0;
  }
  obtainQuery();
});
function obtainQuery() {
  let dormitoryUserQuery = localStorage.getItem('dormitoryUserQuery');
  console.log('我cnim宿舍个人考核', dormitoryUserQuery);
  if (dormitoryUserQuery && dormitoryUserQuery !== null) {
    let dormitoryUserQueryJson = JSON.parse(dormitoryUserQuery);

    optionList.value = dormitoryUserQueryJson.optionList;
    optionList.value.roomList = dormitoryUserQueryJson.optionList.centerRoomList;
    activeKey.value = dormitoryUserQueryJson.activeKey;
    formState.value = dormitoryUserQueryJson.formState;

    if (!dormitoryUserQuery || dormitoryUserQuery === null || dormitoryUserQuery === undefined) {
      dayCreateValue.value = [
        dayjs(moment().format('YYYY-MM-DD 00:00')),
        dayjs(moment().format('YYYY-MM-DD 23:59'))
      ];
      formState.value.createValue = dayCreateValue.value;
    } else {
      if (
        dormitoryUserQueryJson.examineStartTime &&
        dormitoryUserQueryJson.examineStartTime !== null
      ) {
        dayCreateValue.value = [
          dayjs(moment().format(dormitoryUserQueryJson.examineStartTime)),
          dayjs(moment().format(dormitoryUserQueryJson.examineStopTime))
        ];
      } else {
        dayCreateValue.value = [];
      }

      formState.value.createValue = dayCreateValue.value;
    }
    filterChangeRef.value.gradeAndClass = dormitoryUserQueryJson.gradeAndClass;
    filterChangeRef.value.sectionList = dormitoryUserQueryJson.sectionList;
    filterChangeRef.value.gradeAndClassText = dormitoryUserQueryJson.gradeAndClassText;
    console.log('ojbk----', formState.value);
    console.log('dormitoryUserQueryJson', dormitoryUserQueryJson);
    console.log('activeKey.value', activeKey.value);
    // if (
    //   formState.value.gradeId &&
    //   formState.value.gradeId !== null &&
    //   formState.value.gradeId !== undefined
    // ) {
    //   classList({ gradeId: formState.value.gradeId }).then(res => {
    //     if (res.data.code === 200) {
    //       // if (stateUser.value.identity !== 8) {
    //       console.log(
    //         stateUser.value.classInfoList.filter(v => v.gradeId === formState.value.gradeId)
    //       );
    //       console.log(formState.value.gradeId);
    //       console.log(stateUser.value.classInfoList);
    //       let arr = stateUser.value.classInfoList.filter(
    //         v => v.gradeId === formState.value.gradeId
    //       )[0].classIdList;
    //       let list = [];
    //       res.data.data.forEach(v => {
    //         if (arr.indexOf(v.id) !== -1) list.push(v);
    //       });
    //       res.data.data = list;
    //       // }
    //       optionList.value.classList = res.data.data;
    //       console.log('[[[[[[[[[[[[[[[[');
    //       if (
    //         localStorageSchoolId === '346001568933441537' ||
    //         localStorageSchoolId === '221954838718582784'
    //       ) {
    //         formState.value.classId = null;
    //       } else {
    //         formState.value.classId = dormitoryUserQueryJson.classId;
    //       }
    //       formState.value.classId = dormitoryUserQueryJson.classId;
    //     }
    //   });
    // }
    console.log('optionList.value.roomList', optionList.value.roomList);
    if (
      formState.value.dormitoryId &&
      formState.value.dormitoryId !== null &&
      optionList.value.roomList.length === 0
    ) {
      getFloorList(formState.value.dormitoryId);
    }
  } else {
    getRoomBedNum();
    getDormitoryList();
  }
}
const loading = ref(true);
const store = useStore();
const stateUser = computed(() => store.state.user.STATE_USER);
// const stateUser = ref(JSON.parse(localStorage.getItem('STATE_USER')));
// formState.value.superiorId
const onFinish = (values, status) => {
  console.log('status---', status);
  let parmas = {
    data: {
      superiorId: values,
      studentName: undefined,
      gradeId: undefined,
      classId: undefined,
      dormitoryId: undefined,
      roomId: undefined,
      examineStartTime: formState.value.examineStartTime,
      examineStopTime: formState.value.examineStopTime
    },
    current: 1, // 当前页
    pages: 0, // 总页数
    size: 10, // 当前条数
    total: 0 // 总条数
  };
  console.log('llllllllllllllllllllllll', values);
  if (values === 'all') {
    values = 0;
  }
  let dormitoryUserQuery = localStorage.getItem('dormitoryUserQuery');
  console.log('现在有吗', dormitoryUserQuery);
  if (!dormitoryUserQuery || dormitoryUserQuery === null || dormitoryUserQuery === undefined) {
    if (formState.value.examineStartTime === '') {
      formState.value.examineStartTime = startTime;
    }
    if (formState.value.examineStopTime === '') {
      formState.value.examineStopTime = endTime;
    }
    console.log('wocnm', startTime);

    formState.value.current = parmas.current;
    formState.value.size = parmas.size;

    formState.value.superiorId = values;
    activeKey.value = values;

    if (values === 0) {
      activeKey.value = 'all';
    }
    console.log('租到这里了？', formState.value.superiorId);
    console.log('租到这里了？', activeKey.value);
  }
};

// 获取表格信息
function getTabsList(parmas) {
  getAssessList(parmas).then(res => {
    tableData.value = res.data.data;
    loading.value = false;
    console.log('哦哦哦tableData.valuelorem', tableData.value);
  });
}
function examineTime(dates, dateString) {
  console.log('gzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz', dates);
  formState.value.createValue = dates;
  formState.value.examineStartTime = dateString[0];
  formState.value.examineStopTime = dateString[1];
}

// 下拉选项列表
const optionList = ref({
  dormitoryList: [],
  roomList: [],
  roomBedNum: [],
  gradeList: [],
  classList: [],
  centerRoomList: []
});
// 获取宿舍楼列表
const getRoomBedNum = () => {
  roomBedNum().then(res => {
    if (res.data.code === 200) {
      optionList.value.roomBedNum = res.data.data;
    }
  });
};
// 获取宿舍楼列表
const getDormitoryList = status => {
  getDormitory(0).then(res => {
    if (res.data.code === 200) {
      optionList.value.dormitoryList = res.data.data;
      optionList.value.roomList = res.data.data;
      optionList.value.roomList.forEach(elem => {
        elem.isLeaf = false;
      });
      console.log('popppp', res.data.data);
      console.log('是什么玩意', status);
      if (status === 'reset') {
        optionList.value.roomList = [];
        optionList.value.classList = [];
      }
      setTimeout(() => {
        console.log('是什么玩意222', optionList.value.roomList);
      }, 2000);
    }
  });
};
// 获取宿舍楼层列表
const getFloorList = value => {
  floorList(value).then(res => {
    if (res.data.code === 200) {
      res.data.data.forEach(elem => {
        let obj = {
          name: `${elem.storey}楼`,
          storey: elem.storey,
          id: elem.storey,
          dormitoryId: elem.id,
          floor: elem.floor,
          isLeaf: false
        };
        optionList.value.roomList.push(obj);
      });
    }
  });
};
// 改变宿舍楼回调
const onSelectDormitory = value => {
  formState.value.roomId = [];
  optionList.value.roomList = [];
  if (value !== undefined) {
    getFloorList(value);
  } else {
    getDormitoryList();
  }
};
// 选择房间回调
const onChangeRoom = (value, selectedOptions) => {
  // if (selectedOptions[0].dormitoryId !== undefined) {
  //   formState.value.dormitoryId = selectedOptions[0].dormitoryId;
  // } else {
  //   formState.value.dormitoryId = value[0];
  // }
  console.log('走了清除了马', value);
  if (value !== undefined) {
    if (value.length === 3) {
      formState.value.dormitoryId = value[0];
    }
  } else {
    formState.value.roomId = undefined;
  }
};

// 选择房间异步动态加载
const onLoadDataRoom = selectedOptions => {
  console.log('选择房间异步动态加载', selectedOptions);
  if (!formState.value.dormitoryId) {
    formState.value.dormitoryId = selectedOptions[0].id;
  }

  const targetOption = selectedOptions[selectedOptions.length - 1];
  targetOption.loading = true; // load options lazily
  if (targetOption.dormitoryName) {
    floorList(targetOption.id).then(res => {
      if (res.data.code === 200) {
        targetOption.loading = false;
        targetOption.children = [];
        res.data.data.forEach(elem => {
          let obj = {
            name: `${elem.storey}楼`,
            id: elem.storey,
            storey: elem.storey,
            floor: elem.floor,
            isLeaf: false
          };
          targetOption.children.push(obj);
        });
        optionList.value.roomList = [...optionList.value.roomList];
      }
    });
  }
  if (targetOption.floor) {
    let id = selectedOptions[0].floor ? formState.value.dormitoryId : selectedOptions[0].id;
    floorRoom(id, targetOption.storey).then(res => {
      if (res.data.code === 200) {
        targetOption.loading = false;
        targetOption.children = [];
        res.data.data.forEach(elem => {
          let obj = {
            name: elem.name,
            id: elem.id,
            isLeaf: true
          };
          targetOption.children.push(obj);
        });
        optionList.value.roomList = [...optionList.value.roomList];
      }
    });
  }
  console.log('optionList.value.roomList', optionList.value.roomList);
  optionList.value.centerRoomList = optionList.value.roomList;
};
// 获取年级列表
const getGradeList = async () => {
  console.log('opopopopoooooooooooooo');
  await gradeList().then(async res => {
    if (res.data.code === 200) {
      console.log(stateUser.value);
      if (stateUser.value.identity !== 8) {
        let arr = stateUser.value.classInfoList.map(v => v.gradeId);
        let list = [];
        res.data.data.forEach(v => {
          if (arr.indexOf(v.gradeId) !== -1) list.push(v);
        });
        res.data.data = list;
      }
      optionList.value.gradeList = res.data.data;
      if (stateUser.value.identity !== 8) {
        if (
          localStorageSchoolId === '346001568933441537' ||
          localStorageSchoolId === '221954838718582784'
        ) {
          formState.value.gradeId = null;
        } else {
          formState.value.gradeId = optionList.value.gradeList.length
            ? optionList.value.gradeList[0].gradeId
            : null;
        }

        optionList.value.classList = [];
        await classList({ gradeId: formState.value.gradeId }).then(res => {
          if (res.data.code === 200) {
            // if (stateUser.value.identity !== 8) {
            console.log(
              stateUser.value.classInfoList.filter(v => v.gradeId === formState.value.gradeId)
            );
            console.log(formState.value.gradeId);
            console.log(stateUser.value.classInfoList);
            let arr = stateUser.value.classInfoList.filter(
              v => v.gradeId === formState.value.gradeId
            )[0].classIdList;
            let list = [];
            res.data.data.forEach(v => {
              if (arr.indexOf(v.id) !== -1) list.push(v);
            });
            res.data.data = list;
            // }
            optionList.value.classList = res.data.data;
            if (
              localStorageSchoolId === '346001568933441537' ||
              localStorageSchoolId === '221954838718582784'
            ) {
              formState.value.classId = null;
            } else {
              formState.value.classId = optionList.value.classList.length
                ? optionList.value.classList[0].id
                : null;
            }
          }
        });
      }
      onSearch();
    }
  });
};
// 选择年级改变回调
const onChangeGrade = value => {
  formState.value.classId = undefined;
  optionList.value.classList = [];
  classList({ gradeId: value }).then(res => {
    if (res.data.code === 200) {
      if (stateUser.value.identity !== 8) {
        console.log(
          stateUser.value.classInfoList.filter(v => v.gradeId === formState.value.gradeId)
        );
        console.log(formState.value.gradeId);
        console.log(stateUser.value.classInfoList);
        let arr = stateUser.value.classInfoList.filter(
          v => v.gradeId === formState.value.gradeId
        )[0].classIdList;
        let list = [];
        res.data.data.forEach(v => {
          if (arr.indexOf(v.id) !== -1) list.push(v);
        });
        res.data.data = list;
      }
      optionList.value.classList = res.data.data;

      formState.value.classId = optionList.value.classList.length
        ? optionList.value.classList[0].id
        : null;

      // if (
      //   localStorageSchoolId === '346001568933441537' ||
      //   localStorageSchoolId === '221954838718582784'
      // ) {
      //   formState.value.classId = '';
      // } else {

      // }
    }
  });
};
const rankingState = ref(false);
const btnLoading = ref(false);
// 导出
const leadingOut = debounce(function () {
  console.log('走这个导出了吗');
  btnLoading.value = true;
  if (activeKey.value === 'all' && rankingState.value === true) {
    if (selectedRows.value.length <= 0) {
      btnLoading.value = false;
      Message.warning('请至少选择一条导出的数据');
    } else {
      // 根据排名字段排序
      changeScoreRank();

      let objRank = {
        studentIds: [],
        scoreRankList: [],
        superiorId: 0,
        examineStartTime: formState.value.examineStartTime, // 检查时间开始
        examineStopTime: formState.value.examineStopTime, // 检查时间结束
        scoreRankAsc: !rankingOrder.value // 排序
      };

      selectedRows.value.forEach(item => {
        console.log('aaaaaaaa', item);
        objRank.studentIds.push(item.studentUserId);
        objRank.scoreRankList.push(item.scoreRank);
      });
      exportRankStudentExamine(objRank)
        .then(res => {
          let url = window.URL.createObjectURL(res.data);
          let a = document.createElement('a');
          document.body.appendChild(a);
          a.href = url;
          a.download = '综合考核排名.xls';
          a.click();
          btnLoading.value = false;
          window.URL.revokeObjectURL(url);
        })
        .catch(() => {
          btnLoading.value = false;
        });
    }
  } else if (activeKey.value === 'all') {
    console.log(selectedRows.value, '33333');
    if (selectedRows.value.length <= 0) {
      btnLoading.value = false;
      Message.warning('请至少选择一条导出的数据');
    } else {
      let obj = {
        studentUserIdList: [],
        examineStartTime: formState.value.examineStartTime, // 检查时间开始
        examineStopTime: formState.value.examineStopTime // 检查时间结束
      };
      selectedRows.value.forEach(item => {
        obj.studentUserIdList.push(item.studentUserId);
      });

      console.log(obj.studentUserIdList, '数据');
      exportSummaryStudentExamine(obj)
        .then(res => {
          let url = window.URL.createObjectURL(res.data);
          let a = document.createElement('a');
          document.body.appendChild(a);
          a.href = url;
          a.download = '个人综合考核.xls';
          a.click();
          btnLoading.value = false;
          window.URL.revokeObjectURL(url);
        })
        .catch(() => {
          btnLoading.value = false;
        });
    }
  } else {
    console.log(activeKey.value);
    if (selectedRows.value.length <= 0) {
      btnLoading.value = false;
      Message.warning('请至少选择一条导出的数据');
    } else {
      let objStudent = {
        superiorId: activeKey.value,
        excelExamineList: selectedRows.value
      };
      exportStudentExamine(objStudent)
        .then(res => {
          let url = window.URL.createObjectURL(res.data);
          let a = document.createElement('a');
          document.body.appendChild(a);
          a.href = url;
          a.download = '学生个人考核.xls';
          a.click();
          btnLoading.value = false;
          window.URL.revokeObjectURL(url);
        })
        .catch(() => {
          btnLoading.value = false;
        });
    }
  }
}, 500);
const rankingOrder = ref(true);
// 查看排行
function ranking() {
  rankingState.value = true;
  isStudentLeadingOut.value = true;
  dataForm('order');
  //   console.log('hhhhhhh', orderby(0), dataForm());
}
// 正序
function asc() {
  rankingOrder.value = false;

  orderby(true);
}
// 反序
function desc() {
  rankingOrder.value = true;
  orderby(false);
}
let order = ref(true);
function orderby(orders) {
  console.log('0909099999999999999999999999');
  console.log(orders);
  order.value = orders;
  tableData.value.records = [];
  console.log(orders, 'orders');
  console.log(formState.value, 'formState.value');
  if (formState.value.examineStartTime === '') {
    formState.value.examineStartTime = startTime;
  }
  if (formState.value.examineStopTime === '') {
    formState.value.examineStopTime = endTime;
  }

  let roomId;
  if (
    formState.value.roomId &&
    formState.value.roomId !== undefined &&
    formState.value.roomId !== null
  ) {
    roomId = formState.value.roomId[formState.value.roomId.length - 1];
  } else {
    roomId = undefined;
  }
  let gradeAndClass = filterChangeRef.value.disposeChangeData();
  let objData = {
    superiorId: formState.value.superiorId, // 宿舍楼
    // roomId: formState.value.roomId.length
    //   ? formState.value.roomId[formState.value.roomId.length - 1]
    //   : null, // 房间名称
    roomId: roomId,
    examineStartTime: formState.value.examineStartTime + ':00', // 检查时间开始
    examineStopTime: formState.value.examineStopTime + ':59', // 检查时间结束
    sex: formState.value.sex,
    studentName: formState.value.studentName,
    // gradeId: formState.value.gradeId,
    // classId: formState.value.classId,
    dormitoryId: formState.value.dormitoryId,
    studentState: formState.value.studentState,
    allocationStatus: formState.value.allocationStatus,
    classIdCondition: gradeAndClass
  };
  let obj = [];
  if (orders !== 0) {
    obj = {
      data: objData,
      current: tableData.value.current,
      size: tableData.value.size,
      orders: [
        {
          column: 'scoreRank',
          asc: orders
        }
      ]
    };
  } else {
    obj = {
      data: objData,
      current: tableData.value.current,
      size: tableData.value.size,
      orders: [
        {
          column: 'scoreRank',
          asc: false
        }
      ]
    };
  }
  console.log('选择的数据是什么111', selectedRows.value);
  listRankStudentExamine(obj)
    .then(res => {
      tableData.value = res.data.data;
      loading.value = false;
      console.log(columns.value, tableData.value);
      if (orders === 0) {
        console.log('走了查看排行tableData.value', tableData.value);
        console.log('走了查看排行selectedRows.value', selectedRows.value);
        selectedRows.value.forEach(item0 => {
          tableData.value.records.forEach(item1 => {
            if (item0.studentUserId === item1.studentUserId) {
              item0.scoreRank = item1.scoreRank;
            }
          });
        });
        // changeScoreRank()
      }
    })
    .catch(() => {
      loading.value = false;
    });
  // formState.value.examineStartTime = '';
  // formState.value.examineStopTime = '';
  console.log('选择的数据是什么222', selectedRows.value);
  // 正序是 true
  // 反序是 false
  // orders
  console.log('正反', orders);
  console.log('sjbwy', rankingOrder.value);

  // if (orders === false || rankingOrder.value === true) {
  //   selectedRows.value.sort((a, b) => {
  //     return a.scoreRank < b.scoreRank ? 1 : -1;
  //   });
  // } else if (orders === true || rankingOrder.value === false) {
  //   console.log('--------------------------==');
  //   selectedRows.value.sort((a, b) => {
  //     return a.scoreRank > b.scoreRank ? 1 : -1;
  //   });
  // }
  console.log('选择的数据是什么33', selectedRows.value);
}
// 根据排名字段排序
const changeScoreRank = () => {
  if (rankingOrder.value === true) {
    selectedRows.value.sort((a, b) => {
      return a.scoreRank < b.scoreRank ? 1 : -1;
    });
  } else {
    selectedRows.value.sort((a, b) => {
      return a.scoreRank > b.scoreRank ? 1 : -1;
    });
  }
};

function close() {
  rankingState.value = false;
  dataForm();
  onFinish(activeKey.value);
  console.log(3333);
  onSearch();
}
// 日期转换
// function rTime(date) {
//   return new Date(date + 8 * 3600 * 1000)
//     .toISOString()
//     .replace(/T/g, ' ')
//     .replace(/\.[\d]{3}Z/, '');
// }

// tabs改变回调
async function onTabsValue(e, status) {
  // formState.value.superiorId activeKey.value
  console.log('eee', e);
  console.log('status', status);
  searchStatus.value = 0;
  let dormitoryUserQuery = localStorage.getItem('dormitoryUserQuery');
  if (status * 1 === 1) {
    localStorage.removeItem('dormitoryUserQuery');
    dayCreateValue.value = [
      dayjs(moment().format('YYYY-MM-DD 00:00')),
      dayjs(moment().format('YYYY-MM-DD 23:59'))
    ];
    formState.value.examineStartTime = dayCreateValue.value[0];
    formState.value.examineStopTime = dayCreateValue.value[1];
    console.log('09099999', formState.value.examineStartTime);
    await resetForm('reset');
  }

  // formState.value.superiorId = e.id; createValue

  tableData.value.records = [];
  console.log('tabs改变回调', e.id);
  console.log('tabs改变回调lorem', dayCreateValue.value);
  loading.value = true;
  formState.value.createValue = dayCreateValue.value;
  if (!dormitoryUserQuery || dormitoryUserQuery === null || dormitoryUserQuery === undefined) {
    // formState.value.examineStartTime = '';
    // formState.value.examineStopTime = '';
    activeKey.value = e.id;
    dayCreateValue.value = [
      dayjs(moment().format('YYYY-MM-DD 00:00')),
      dayjs(moment().format('YYYY-MM-DD 23:59'))
    ];
    formState.value.examineStartTime = dayjs(dayCreateValue.value[0]).format('YYYY-MM-DD 00:00');
    formState.value.examineStopTime = dayjs(dayCreateValue.value[1]).format('YYYY-MM-DD 23:59');
    filterChangeRef.value.gradeAndClass = [];
    console.log('09099999----', dayjs(dayCreateValue.value[0]).format('YYYY-MM-DD 00:00'));
  } else {
    activeKey.value = JSON.parse(dormitoryUserQuery).activeKey;
  }
  // formState.value.superiorId = e.id;

  selectedRows.value = [];
  selectedRowKeys.value = [];

  if (e.id !== undefined) {
    onFinish(e.id, 'tab');
    if (!dormitoryUserQuery || dormitoryUserQuery === null || dormitoryUserQuery === undefined) {
      activeKey.value = e.id;
    }
    rankingState.value = false;
  } else {
    onFinish('all', 'tab');
    activeKey.value = 'all';
    rankingState.value = false;
  }
  dataForm();

  // if (!dormitoryUserQuery || dormitoryUserQuery === null || dormitoryUserQuery === undefined) {
  //   await resetForm();
  // }

  // await getGradeList();

  onSearch();
}

// 表格多选
const selectedRowKeys = ref([]);
const selectedRows = ref([]);
// table 多选回调
const onSelectChange = (rowKeys, rows) => {
  selectedRowKeys.value = rowKeys;
  selectedRows.value = rows;
  console.log(selectedRows.value);
};
// 是否选择导出学生
const isStudentLeadingOut = ref(false);
const delStateClick = computed(() => {
  let str = '';
  if (isStudentLeadingOut.value) str = 'primary';
  return str;
});
watch(selectedRowKeys, value => {
  if (value.length) {
    isStudentLeadingOut.value = true;
  } else {
    isStudentLeadingOut.value = false;
  }
});
// 指定每页条数
const pageSizeOptions = ref(['10', '20', '30', '40', '50', '100', '500', '1000']);
// 分页发生改变
const onChangePagination = value => {
  let roomId;
  if (
    formState.value.roomId &&
    formState.value.roomId !== undefined &&
    formState.value.roomId !== null
  ) {
    roomId = formState.value.roomId[formState.value.roomId.length - 1];
  } else {
    roomId = undefined;
  }
  let gradeAndClass = filterChangeRef.value.disposeChangeData();
  let obj = {
    data: {
      superiorId: formState.value.superiorId, // 宿舍楼
      // roomId: formState.value.roomId.length
      //   ? formState.value.roomId[formState.value.roomId.length - 1]
      //   : null, // 房间名称
      roomId: roomId,
      examineStartTime: formState.value.examineStartTime, // 检查时间开始
      examineStopTime: formState.value.examineStopTime, // 检查时间结束
      sex: formState.value.sex,
      studentName: formState.value.studentName,
      // gradeId: formState.value.gradeId,
      // classId: formState.value.classId,
      dormitoryId: formState.value.dormitoryId,
      studentState: formState.value.studentState,
      allocationStatus: formState.value.allocationStatus,
      classIdCondition: gradeAndClass
    },
    current: tableData.value.current,
    size: tableData.value.size
  };
  formState.value.current = tableData.value.current;
  formState.value.size = tableData.value.size;
  if (formState.value.superiorId !== 0) {
    getTabsList(obj);
  } else if (activeKey.value === 'all' && !rankingState.value) {
    getTabsList(obj);
  } else {
    obj = {
      data: {
        superiorId: formState.value.superiorId, // 宿舍楼
        // roomId: formState.value.roomId.length
        //   ? formState.value.roomId[formState.value.roomId.length - 1]
        //   : null, // 房间名称
        roomId: roomId,
        examineStartTime: formState.value.examineStartTime, // 检查时间开始
        examineStopTime: formState.value.examineStopTime, // 检查时间结束
        sex: formState.value.sex,
        studentName: formState.value.studentName,
        // gradeId: formState.value.gradeId,
        // classId: formState.value.classId,
        dormitoryId: formState.value.dormitoryId,
        studentState: formState.value.studentState,
        allocationStatus: formState.value.allocationStatus,
        classIdCondition: gradeAndClass
      },
      current: tableData.value.current,
      size: tableData.value.size,
      orders: [
        {
          column: 'scoreRank',
          asc: order.value
        }
      ]
    };
    listRankStudentExamine(obj).then(res => {
      tableData.value = res.data.data;
      loading.value = false;
      console.log(columns.value, tableData.value);
    });
  }
};
// 查看详情
const onDeta = (id, studentUserId, roomId) => {
  saveQuery();
  let path = null;
  if (formState.value.examineStartTime === '') {
    formState.value.examineStartTime = startTime;
  }
  if (formState.value.examineStopTime === '') {
    formState.value.examineStopTime = endTime;
  }
  if (activeKey.value === 'all') {
    let objs = {
      studentUserId: studentUserId.toString(),
      examineStartTime: formState.value.examineStartTime,
      examineStopTime: moment(formState.value.examineStopTime).format('YYYY-MM-DD') + ' 23:59:59'
    };
    getStudentDayExamineDetail(objs).then(res => {
      if (res.data.code === 200) {
        // path = '/aaa';
        router.push({
          path: '/check/dormitoryPersonal/allDeta',
          query: {
            studentUserId: studentUserId,
            roomId: roomId, // 房间id
            examineStartTime: formState.value.examineStartTime, // 检查时间开始
            examineStopTime: formState.value.examineStopTime // 检查时间结束
          }
        });
      } else {
        message.error(res.data.msg);
        // 在这要刷新列表
        onSearch();
      }
    });
  } else {
    path = '/check/dormitoryPersonal/disciplineDeta';
    let obj = {
      studentUserId: studentUserId.toString(),
      examineId: id.toString(),
      superiorId: activeKey.value.toString()
    };
    getStudentExamineDetails(obj).then(res => {
      if (res.data.code === 200) {
        router.push({
          path,
          query: {
            studentUserId: studentUserId,
            examineId: id, // 考核ID
            superiorId: activeKey.value // 考核项目顶级分类ID
          }
        });
      } else {
        message.error(res.data.msg);
        // 在这要刷新列表
        onSearch();
      }
    });
  }
};
function saveQuery() {
  let gradeAndClass = filterChangeRef.value.disposeChangeData();
  let json = {
    activeKey: activeKey.value,
    size: formState.value.size, // 10
    current: formState.value.current, // 1
    superiorId: formState.value.superiorId,
    examineStartTime: formState.value.examineStartTime, // 检查时间开始
    examineStopTime: formState.value.examineStopTime, // 检查时间结束
    sex: formState.value.sex,
    studentName: formState.value.studentName,
    // gradeId: formState.value.gradeId,
    // classId: formState.value.classId,
    dormitoryId: formState.value.dormitoryId,
    studentState: formState.value.studentState,
    allocationStatus: formState.value.allocationStatus,
    formState: formState.value,
    optionList: optionList.value,
    classIdCondition: gradeAndClass,
    gradeAndClass: filterChangeRef.value.gradeAndClass,
    sectionList: filterChangeRef.value.sectionList,
    gradeAndClassText: filterChangeRef.value.gradeAndClassText
  };
  console.log('保存的时候', json);
  localStorage.setItem('dormitoryUserQuery', JSON.stringify(json));
}
// onReset
const onReset = debounce(async () => {
  searchStatus.value = 0;
  console.log('-------------------------------------------');
  formState.value.size = 10;
  formState.value.createValue = dayCreateValue.value;
  formState.value.examineStartTime = startTime;
  formState.value.examineStopTime = endTime;
  // formRef.value.resetFields();
  formState.value.dormitoryId = undefined;
  formState.value.roomId = [];
  formState.value.studentName = undefined;
  formState.value.gradeId = null;
  formState.value.classId = null;
  filterChangeRef.value.gradeAndClass = [];
  formState.value.createValue = [
    dayjs(moment().format('YYYY-MM-DD 00:00')),
    dayjs(moment().format('YYYY-MM-DD 23:59'))
  ];
  optionList.value.roomList = [];
  onSearch();
  getDormitoryList('reset');
}, 500);
// 时间设置
let startTime = moment(new Date(new Date(new Date().toLocaleDateString()).getTime())).format(
  'YYYY-MM-DD HH:mm:ss'
);
let endTime = moment(
  new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)
).format('YYYY-MM-DD HH:mm:ss');
// 重置
const resetForm = () => {
  formState.value.createValue = dayCreateValue.value;
  formState.value.examineStartTime = startTime;
  formState.value.examineStopTime = endTime;
  // formRef.value.resetFields();
  formState.value.dormitoryId = undefined;
  formState.value.roomId = [];
  formState.value.studentName = undefined;
  formState.value.gradeId = undefined;
  formState.value.classId = undefined;
  filterChangeRef.value.gradeAndClass = [];
  // let obj = {
  //   data: formState.value,
  //   current: tableData.value.current,
  //   size: tableData.value.size
  // };

  dayCreateValue.value = [
    dayjs(moment().format('YYYY-MM-DD 00:00')),
    dayjs(moment().format('YYYY-MM-DD 23:59'))
  ];
  console.log(22222);
  getDormitoryList('reset');
};

// function getDateRange(startDate, endDate) {
//   return [moment(startDate, 'YYYY-MM-DD HH:mm'), moment(endDate, 'YYYY-MM-DD HH:mm')];
// }
const dataColumns = reactive([
  {
    key: 'studentName',
    title: '姓名',
    dataIndex: 'studentName',
    scopedSlots: { customRender: 'studentName' },
    fixed: 'left'
  },
  {
    key: 'className',
    title: '学段/年级/班级',
    dataIndex: 'className',
    scopedSlots: { customRender: 'className' }
  },
  {
    key: 'dormitoryName',
    title: '宿舍楼',
    dataIndex: 'dormitoryName',
    scopedSlots: { customRender: 'dormitoryName' }
  },
  {
    key: 'roomName',
    title: '房间名',
    dataIndex: 'roomName',
    scopedSlots: { customRender: 'roomName' }
  },
  {
    key: 'markScore',
    title: '得/扣分',
    dataIndex: 'markScore',
    scopedSlots: { customRender: 'markScore' }
  }
]);
const dataActive = reactive({
  title: '操作',
  key: 'action',
  dataIndex: 'action',
  scopedSlots: { customRender: 'action' },
  fixed: 'right',
  width: 100
});

let columns = ref([]);
const dataForm = type => {
  if (activeKey.value === 'all' && rankingState.value === true) {
    columns.value = [
      reactive({
        key: 'scoreRank',
        title: '排名',
        fixed: 'left',
        dataIndex: 'scoreRank',
        scopedSlots: { customRender: 'scoreRank' }
      }),
      ...dataColumns,
      dataActive
    ];
  } else if (activeKey.value !== 'all') {
    columns.value = [
      ...dataColumns,
      reactive(
        {
          key: 'itemNames',
          title: '扣分项',
          dataIndex: 'itemNames',
          scopedSlots: { customRender: 'itemNames' }
        },
        {
          key: ' xamineTime',
          title: '检查时间',
          dataIndex: 'examineTime',
          scopedSlots: { customRender: 'examineTime' }
        },
        {
          key: 'markUserName',
          title: '检查人',
          dataIndex: 'markUserName',
          scopedSlots: { customRender: 'markUserName' }
        }
      ),
      dataActive
    ];
  } else {
    columns.value = [...dataColumns, dataActive];
  }
  if (type === 'order') orderby(0);
};

// 表单查询
const formRef = ref();

// 查询 按钮
const onSearch = debounce(status => {
  console.log('aaaaa', formState.value);
  console.log('aaa', optionList.value);
  // 手动点击
  if (status * 1 === 1) {
    searchStatus.value = 1;
    formState.value.current = 1;
  }
  loading.value = true;
  // 置空表格可视清空 和已选择的数据
  selectedRowKeys.value = [];
  selectedRows.value = [];
  if (activeKey.value === 'all' && rankingState.value === true) {
    orderby(!rankingOrder.value);
  } else {
    // formState.value.roomId.length
    //       ? formState.value.roomId[formState.value.roomId.length - 1]
    //       : null // 房间名称
    let roomId;
    if (
      formState.value.roomId &&
      formState.value.roomId !== undefined &&
      formState.value.roomId !== null
    ) {
      roomId = formState.value.roomId[formState.value.roomId.length - 1];
    } else {
      roomId = undefined;
    }
    let gradeAndClass = filterChangeRef.value.disposeChangeData();
    let obj = {
      data: {
        superiorId: formState.value.superiorId, // 宿舍楼
        roomId: roomId,
        examineStartTime: formState.value.examineStartTime, // 检查时间开始
        examineStopTime: formState.value.examineStopTime, // 检查时间结束
        sex: formState.value.sex,
        studentName: formState.value.studentName,
        // gradeId: formState.value.gradeId,
        // classId: formState.value.classId,
        dormitoryId: formState.value.dormitoryId,
        studentState: formState.value.studentState,
        allocationStatus: formState.value.allocationStatus,
        classIdCondition: gradeAndClass
      },
      current: formState.value.current,
      size: formState.value.size
    };
    getAssessList(obj).then(res => {
      // tableData.value.records = [];
      tableData.value = res.data.data;
      console.log('ojbk', formState.value);
      console.log('ojbk', activeKey.value);
      console.log('查询出来的数据。。。', tableData.value);
      console.log('查询出来的数据res', res);
      console.log('之前选中的数据', selectedRows.value);

      loading.value = false;
    });
  }
}, 500);

// label样式
// const labelCol = reactive({
//   xs: { span: 4 },
//   sm: { span: 6 }
// });
// const wrapperCol = reactive({
//   xs: { span: 24 },
//   sm: { span: 16 }
// });
const labelCol = reactive({
  xs: { span: 8 },
  xl: { span: 8 },
  xxl: { span: 6 }
});
const wrapperCol = reactive({
  xs: { span: 24 },
  xl: { span: 24 },
  xxl: { span: 24 }
});
const filterChangeRef = ref(null);
</script>

<style lang="less" scoped>
.top,
.below {
  width: 100%;
  padding: 24px 0;
  background: #ffffff;
  border-radius: 4px;
}
.below {
  padding: 24px;
  min-height: 650px;
  .ranking {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #e1dddd;
    padding-bottom: 16px;
    margin-bottom: 16px;
    &-text {
      font-size: 18px;
      font-family: Source Han Sans CN, Source Han Sans CN-Medium;
      font-weight: 500;
      color: #222222;
    }
  }
  .search {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 24px;
    .search-btn-left {
      width: 40%;
      display: flex;
      justify-content: flex-start;
      a-button {
        margin-left: 16px;
      }
    }
    .search-btn-right {
      width: 40%;
      display: flex;
      justify-content: flex-end;
    }
  }
  /deep/.micro-dormitory-empty-normal .micro-dormitory-empty-image {
    height: 100px;
  }
  /deep/.micro-dormitory-empty-img-simple {
    width: 100px;
    height: 80px;
  }
}
.top {
  margin-bottom: 24px;
  .search {
    display: flex;
    justify-content: flex-end;
    margin-right: 22px;
  }
}
.pagination {
  align-items: center;
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}
/deep/.micro-dormitory-tabs-tab {
  font-size: 16px;
  padding: 12px 24px;
}
/deep/.micro-dormitory-select-arrow {
  top: 40%;
}
/deep/.micro-dormitory-select-selection-item {
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  width: 8rem !important;
}
// /deep/.micro-dormitory-cascader-menu {
//   white-space: nowrap !important;
//   overflow: hidden !important;
//   text-overflow: ellipsis !important;
//   width: 270px !important;
// }
/deep/.micro-dormitory-cascader-menu-item-content,
/deep/.micro-dormitory-cascader-menu-item-expand,
/deep/.micro-dormitory-cascader-menu-item {
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  width: 270px !important;
}
/deep/.micro-dormitory-table-content {
  min-height: 55vh;
}
</style>
